<template>
	<view>
		<view class="u-p-l-30 u-p-r-30">
			<u-form :model="form" :error-type="errorType" ref="uForm">
				<u-form-item label="昵称" prop="name" required>
					<u-input v-model="form.name" />
				</u-form-item>
			</u-form>
		</view>
		<view class="btn">
			<u-button @click="submit">修改</u-button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				errorType: ['message'],
				nickname: '',
				form: {
					name: '',
				},
				rules: {
					name: [{
						required: true,
						message: '请输入姓名',
						// 可以单个或者同时写两个触发验证方式 
						trigger: ['change', 'blur'],
					}],

				},
			}
		},
		methods: {
			submit() {
				this.$refs.uForm.validate(valid => {
					if (valid) {

						console.log('验证通过');
						const db = uniCloud.database();
						let collection = db.collection('uni-id-users')
						let res = collection.where({
								username: this.username
							})
							.update({
								nickname: this.form.name
							})
							this.$u.toast('修改成功')
								try {
									uni.setStorageSync('nickname', this.form.name);
								} catch (e) {
									// error
								}
					} else {
						console.log('验证失败');
					}
				});
			}
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules);
			try {
				const nickname = uni.getStorageSync('nickname');
				if (nickname) {
					this.nickname = nickname
					this.form.name = nickname
				}
			} catch (e) {
				// error
			}
		}
	}
</script>

<style>

</style>
